export default function useBt() {

	const serviceUUID = '0000F040-0000-1000-8000-00805F9B34FB'; // 主服务UUID
	const writeUUID = '0000F041-0000-1000-8000-00805F9B34FB'; // 写属性UUID
	const readUUID = '0000F042-0000-1000-8000-00805F9B34FB'; // 读属性UUID

	// 蓝牙已初始化
	const adapterOpend = ref(false)
	// 搜索状态
	const startSearch = ref(false)

	const findTimer = ref(null)

	// 蓝牙连接状态
	const connectStatus = ref(false)

	// 设备列表
	const deviceList = ref([])

	// 设备Id
	const deviceId = ref('')

	// * 主服务 UUID 0000F040-0000-1000-8000-00805F9B34FB
	// * 写属性 UUID 0000F041-0000-1000-8000-00805F9B34FB 
	// * 读属性(非通知)UUID 0000F042-0000-1000-8000-00805F9B34FB

	/**
	 * 统一安卓与IOS端deviceId展示
	 * @param advertisData 
	 * 在安卓设备中，获取到的 deviceId 为设备 MAC 地址，iOS 上则为设备 uuid，
	 * 因此为了展示一致需要将ios的展示进行输入（当然IOS的连接还是得用获取到的uuid）
	 */
	function uuid2Mac(advertisData) {
		if (advertisData) {
			let mac = Array.prototype.map
				.call(new Uint8Array(bf), (x) => ("00" + x.toString(16)).slice(-2))
				.join(":");
			mac = mac.toUpperCase();
			return mac;
		}
	}

	// 初始化蓝牙
	async function initBluetooth() {
		// try {
		// 	stopBluetoothDevicesDiscovery(); // 停止扫描
		// } catch (e) {
		// 	//TODO handle the exception
		// }
		return new Promise((resolve, reject) => {
			if (adapterOpend.value) {
				console.log("蓝牙适配器已打开")
				resolve(true)
				return
			}
			uni.openBluetoothAdapter({
				success(res) {
					adapterOpend.value = true
					console.log("=====*****蓝牙适配器已打开1")
					resolve(true)
				},
				fail(error) { //用来判断蓝牙是否已打开
					console.log('initBluetooth error', error)
					if (error.errMsg.includes('already opened')) {
						adapterOpend.value = true
						console.log("=====*****蓝牙适配器已打开2")
						resolve(true)
						return;
					}
					reject(error)
					adapterOpend.value = false
					console.log("=====*****蓝牙适初始化失败", error)
				}
			})
		})
	}

	// 关闭蓝牙

	async function closeBluetooth() {
		return new Promise((resolve, reject) => {
			uni.closeBluetoothAdapter({
				success(res) {
					resolve(res)
				},
				fail(err) {
					reject(err)
				}
			})
		})
	}

	/**
	 * 开始搜寻蓝牙
	 * @param options 
	 * @param {array} options.services  要搜索的蓝牙设备主服务的 UUID 列表
	 */
	async function startBluetoothDevicesDiscovery(options) {
		return new Promise((resolve, reject) => {
			if (startSearch.value) {
				console.log("已开启蓝牙扫描，勿重复开启")
				resolve(true)
				return
			}
			startSearch.value = true
			uni.startBluetoothDevicesDiscovery({
				allowDuplicatesKey: true,
				// services: options.services,
				success(res) {
					console.log('搜索成功', res);
					resolve(true)
				},
				fail(error) {
					console.log('搜索失败', error);
					reject(error)
					startSearch.value = false
				},
			})
		})
	}

	/**
	 * 监听搜索到的设备
	 * @param options 
	 * options.keywords  蓝牙名称筛选关键字
	 */
	async function onBluetoothDeviceFound(options) {
		return new Promise((resolve, reject) => {
			let {
				keywords
			} = options
			// 超时自动结束
			findTimer.value = setTimeout(() => {
				clearTimeout(findTimer.value)
				if (!connectStatus.value) {
					stopBluetoothDevicesDiscovery(); // 停止扫描
					reject({
						success: false
					})
					console.log('蓝牙扫描超时，自动关闭任务')
				}
			}, 3000); //时间根据自己的需求定
			uni.onBluetoothDeviceFound(res => {
				let devices = res.devices;
				// console.log('devices', res)
				for (let i = 0; i < devices.length; i++) {
					let device = devices[i];
					if (!device.name && !device.localName) {
						return
					}
					// console.log('device', device)
					// 获取设备MAC地址，并根据关键字过滤
					// let systemInfo = uni.getSystemInfoSync()
					// let iosDevice = systemInfo.system.toLowerCase().indexOf("ios") > -1;
					// let deviceMac = iosDevice ? uuid2Mac(device.advertisData) : device.deviceId
					// keywords
					if (keywords === device.name) {
						// 获取广播数据
						// const advertisementData = new Uint8Array(device.advertisData);
						const advertisementData = new Uint8Array(device.advertisData);
						console.log('广播数据:', advertisementData);
						
						// 解析固定标识符
						const identifier = (advertisementData[0] << 8) | advertisementData[1]; // 0x5A58
						console.log('标识符:', identifier.toString(16)); // 输出 5A58
						
						// 解析蓝牙 MAC 地址
						const macAddress = advertisementData.slice(2, 8);
						console.log('MAC 地址:', macAddress.map(byte => byte.toString(16)).join(':')); // 输出 D6:09:03:06:7C:4B
						
						// 解析电池电压
						const batteryVoltage = (advertisementData[8] << 8) | advertisementData[9]; // 电压值
						console.log('电池电压 (mV):', batteryVoltage); // 输出 0x0FFA (十进制: 4090mV)
						
						// 解析电池电量百分比
						const batteryLevel = advertisementData[10]; // 电量百分比
						console.log('电池电量 (%):', batteryLevel); // 输出 100%
						
						stopBluetoothDevicesDiscovery()
						resolve({
							...device,
							// deviceMac,
							success: true
						})
						break;
					}
				}
			})

		})
	}

	function stopBluetoothDevicesDiscovery() {
		startSearch.value = false
		uni.stopBluetoothDevicesDiscovery(); // 停止扫描
	}

	/**
	 * 处理蓝牙连接
	 * @param {string} options.deviceId 蓝牙设备id，连接用
	 */
	async function createBLEConnection(options) {
		return new Promise((resolve, reject) => {
			let {
				deviceId: deviceCode
			} = options;
			deviceId.value = deviceCode
			console.log('---deviceId', deviceId.value)
			// if (connectStatus.value) {
			// 	uni.closeBLEConnection({
			// 		deviceId
			// 	})
			// }
			let timeout = 3000 //根据自己需求去定
			console.log('开始连接蓝牙--', deviceId.value)
			// _this.stopBLEDevicesTask() // todo
			uni.createBLEConnection({
				deviceId: deviceId.value,
				timeout,
				success(res) {
					if (res.errCode === 0) {
						console.log('蓝牙连接成功-----', res)
						connectStatus.value = true
						resolve(res)
					} else {
						console.log('蓝牙连接失败-----', res)
						connectStatus.value = false
						reject(res)
					}
				},
				fail(err) {
					console.log('蓝牙连接失败-----', err)
					connectStatus.value = false
					reject(err)
				}
			})
		})
	}

	/**
	 * 连接成功后，要获取蓝牙的所有服务 进而根据项目需求的服务 去获取对应的特征 来进行读写操
	 * @param deviceId  蓝牙设备Id，来自createBLEConnection调用
	 */
	async function getBLEDeviceServices(deviceId = '') {
		return new Promise((resolve, reject) => {
			uni.getBLEDeviceServices({
				deviceId,
				success(res) {
					console.log('getBtDeviceServices res：', res)
					resolve({
						sucess: true
					})
				},
				fail: (res) => {
					reject({
						sucess: false,
						data: res.errMsg
					})
					console.log("服务获取失败------------->", res.errMsg);
				},
			});
		})
	}


	// 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
	// https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth-ble/uni.getBLEDeviceCharacteristics.html
	async function getBLEDeviceCharacteristics() {
		return new Promise((resolve, reject) => {
			uni.getBLEDeviceCharacteristics({
				deviceId: deviceId.value,
				serviceId: serviceUUID,
				success: (res) => {
					console.log('Characteristics found:', res.characteristics);
					resolve()
				},
				fail: (err) => {
					console.error('Failed to get characteristics:', err);
					reject(err)
				}
			});
		})
	}

	// 检测是否连接中, 如果未连接则尝试重新连接
	async function checkAndReconnectDevice(deviceId) {
		return new Promise((resolve, reject) => {
			uni.getConnectedBluetoothDevices({
				services: [serviceUUID],
				success: (res) => {
					const isConnected = res.devices.some(device => device.deviceId ===
						deviceId);
					console.log('getConnectedBluetoothDevices', res)
					console.log('deviceId', `${isConnected} --- ${deviceId}`)
					if (!isConnected) {
						resolve(false)
						console.log('Device not connected, reconnecting...');
					} else {
						console.log('Device already connected');
						resolve(true)
					}
				},
				fail: (err) => {
					resolve(false)
				}
			});
		})
	};

	// 读取充电状态
	async function readChargeStatus() {
		return new Promise(async (resolve, reject) => {
			try{
				await getBLEDeviceServices()
				await getBLEDeviceCharacteristics()
			}
			catch(e){
				//TODO handle the exception
			}	
			// 监听特征值变化
			uni.onBLECharacteristicValueChange((res) => {
				console.log('Characteristic value changed:', res);
				const status = new DataView(res.value).getUint8(19);
				if (status === 0x46) {
					console.log('charging data', res.value);
					console.log('Charging in progress');
					resolve({
						status: true,
						charging: true,
						hours: new DataView(res.value).getUint8(2),
						minutes: new DataView(res.value).getUint8(3),
					})
				} else {
					console.log('Not charging');
					resolve({
						status: true,
						charging: false,
						hours: 0,
						minutes: 0,
					})
				}
			});
			uni.readBLECharacteristicValue({
				deviceId: deviceId.value,
				serviceId: serviceUUID,
				characteristicId: readUUID,
				success: (res) => {
					console.log('Read characteristic value request sent successfully', res);
				},
				fail: (err) => {
					reject({
						status: false,
						charging: false,
						hours: 0,
						minutes: 0,
						errMsg: `${err.errCode}:${err.errMsg}`
					})
					console.error('Failed to read charge status:', err);
				}
			});
		});
	};


	async function sendCargeCommand(hours, minutes) {
		return new Promise((resolve, reject) => {
			const buffer = new ArrayBuffer(20);
			const dataView = new DataView(buffer);
			dataView.setUint8(0, 0xFE); // Header
			dataView.setUint8(1, 0xD5); // Command
			dataView.setUint8(2, hours); // Hours
			dataView.setUint8(3, minutes); // Minutes
			dataView.setUint8(19, 0x45); // Status byte

			console.log('Sending charge command:', dataView);

			uni.writeBLECharacteristicValue({
				deviceId: deviceId.value,
				serviceId: serviceUUID,
				characteristicId: writeUUID,
				value: buffer,
				writeType: 'write',
				success: () => {
					console.log('Charge command sent successfully');
					resolve()
				},
				fail: (err) => {
					console.error('Failed to send charge command:', err);
					reject(err)
				}
			});
		});
	}

	return {
		initBluetooth,
		closeBluetooth,
		startBluetoothDevicesDiscovery,
		onBluetoothDeviceFound,
		createBLEConnection,
		getBLEDeviceServices,
		getBLEDeviceCharacteristics,
		sendCargeCommand,
		readChargeStatus,
		checkAndReconnectDevice,
	}
}